<?php

/**************************************************************
 *
 *    使用特定function对数组中所有元素做处理
 *    @param  string  &$array     要处理的字符串
 *    @param  string  $function   要执行的函数
 *    @return boolean $apply_to_keys_also     是否也应用到key上
 *    @access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++ $recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }
        
        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter --;
}

/**
 * ************************************************************
 *
 * 将数组转换为JSON字符串（兼容中文）
 *
 * @param array $array
 *            要转换的数组
 * @return string 转换得到的json字符串
 * @access public
 *        
 *         ***********************************************************
 */
function JSON($array)
{
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}

function my_log($content)
{
    $logs = new \Common\Model\LogModel();
    $data = array();
    $data['text'] = $content;
    $logs->add($data);
}

/**
 * 百度短网址
 *
 * @param unknown $url            
 */
function baidu_dwz($url)
{
    return $url;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://dwz.cn/create.php");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = array(
        'url' => $url
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $strRes = curl_exec($ch);
    curl_close($ch);
    $arrResponse = json_decode($strRes, true);
    if ($arrResponse['status'] != 0) {
        /**
         * 错误处理
         */
        $error = iconv('UTF-8', 'GBK', $arrResponse['err_msg']);
        return $url;
    }
    /**
     * tinyurl
     */
    return $arrResponse['tinyurl'];
}


/**
 * 抓https数据
 *
 * @param unknown $url            
 * @param string $data            
 * @param string $timeout            
 */
function https_request($url, $data = null, $timeout = 5000)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (! empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    if ($timeout) {
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    }
    
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    if ($output === false) {
        my_log('Curl error: ' . curl_error($curl).". url:".$url);
    }
    
    curl_close($curl);
    return $output;
}


/**
 * 递归创建文件夹
 *
 * @param unknown $dir            
 * @param number $mode            
 * @return boolean
 */
function mkdirs($dir, $mode = 0755)
{
    if (! is_dir($dir)) {
        if (! mkdirs(dirname($dir))) {
            return false;
        }
        if (! mkdir($dir, $mode)) {
            return false;
        }
    }
    return true;
}

/**
 * 对象转数组
 * @param unknown $obj
 * @return unknown|NULL[]
 */
function objToArr($obj){
    if(!is_object($obj) && !is_array($obj)) {
        return $obj;
    }
    $arr = array();
    foreach($obj as $k => $v){
        $arr[$k] = objToArr($v);
    }
    return $arr;
}


function abslength($str)
{
    if (empty($str)) {
        return 0;
    }
    if (function_exists('mb_strlen')) {
        return mb_strlen($str, 'utf-8');
    } else {
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}

function csubstr($str, $start = 0, $length, $charset = "utf-8")
{
    if (function_exists("mb_substr")) {
        if (mb_strlen($str, $charset) <= $length)
            return $str;
        $slice = mb_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        if (count($match[0]) <= $length)
            return $str;
        $slice = join("", array_slice($match[0], $start, $length));
    }
    return $slice;
}

function smart_resize_image($file, $width = 0, $height = 0, $proportional = false, $output = 'file', $delete_original = true, $use_linux_commands = false)
{
    if ($height <= 0 && $width <= 0) {
        return false;
    }
    $info = getimagesize($file);
    $image = '';

    $final_width = 0;
    $final_height = 0;
    list ($width_old, $height_old) = $info;

    if ($proportional) {
        if ($width == 0)
            $factor = $height / $height_old;
        elseif ($height == 0)
        $factor = $width / $width_old;
        else
            $factor = min($width / $width_old, $height / $height_old);
        $final_width = round($width_old * $factor);
        $final_height = round($height_old * $factor);
    } else {
        $final_width = ($width <= 0) ? $width_old : $width;
        $final_height = ($height <= 0) ? $height_old : $height;
    }

    switch ($info[2]) {
    	case IMAGETYPE_GIF:
    	    $image = imagecreatefromgif($file);
    	    break;
    	case IMAGETYPE_JPEG:
    	    $image = imagecreatefromjpeg($file);
    	    break;
    	case IMAGETYPE_PNG:
    	    $image = imagecreatefrompng($file);
    	    break;
    	default:
    	    return false;
    }

    $image_resized = imagecreatetruecolor($final_width, $final_height);

    if (($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG)) {
        $trnprt_indx = imagecolortransparent($image);
        if ($trnprt_indx >= 0) {
            $trnprt_color = imagecolorsforindex($image, $trnprt_indx);
            $trnprt_indx = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
            imagefill($image_resized, 0, 0, $trnprt_indx);
            imagecolortransparent($image_resized, $trnprt_indx);
        } elseif ($info[2] == IMAGETYPE_PNG) {
            imagealphablending($image_resized, false);
            $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
            imagefill($image_resized, 0, 0, $color);
            imagesavealpha($image_resized, true);
        }
    }

    imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);

    if ($delete_original) {
        if ($use_linux_commands)
            exec('rm ' . $file);
        else
            @unlink($file);
    }

    switch (strtolower($output)) {
    	case 'browser':
    	    $mime = image_type_to_mime_type($info[2]);
    	    header("Content-type: $mime");
    	    $output = NULL;
    	    break;
    	case 'file':
    	    $output = $file;
    	    break;
    	case 'return':
    	    return $image_resized;
    	    break;
    	default:
    	    break;
    }

    switch ($info[2]) {
    	case IMAGETYPE_GIF:
    	    imagegif($image_resized, $output);
    	    break;
    	case IMAGETYPE_JPEG:
    	    imagejpeg($image_resized, $output);
    	    break;
    	case IMAGETYPE_PNG:
    	    imagepng($image_resized, $output);
    	    break;
    	default:
    	    return false;
    }

    return true;
}

/**
 * 获取access_token
 *
 * @return Ambigous <mixed, object>|Ambigous <unknown, mixed, object>|boolean
 */
function get_token( $is_force = false )
{
    if( $is_force==false )
    {
        $data = S("access_token");
        if ( $data ) {
            if( is_array($data) && $data['expire_time'] > time() ){
                $access_token = $data['access_token'];
                return $access_token;
            }else if(  is_string($data) ){
                $access_token = $data;
                return $access_token;
            }
        }
        my_log('get access_token fail from cache in get_token function:'.$data."----".JSON(C('MEMCACHED_SERVER')).'-----'.C('DATA_CACHE_PREFIX')."----".implode($data)."~~~".C('SESSION_PREFIX'));
        return false;
    }
    
    $appId = C('AppID');
    $appSecret = C('AppSecret');
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appId . '&secret=' . $appSecret;
    $rs1 = https_request($url);
    
    $content = "wxhao:".C('WX_HAO').". cache pre :".C('DATA_CACHE_PREFIX').". is_force:".$is_force.". result:".$rs1 .". url:". $url ;
    my_log($content);
    if ($rs1) {
        $rs = json_decode($rs1, true);
        if (is_array($rs) && $rs['access_token']) {
            $access_token = $rs['access_token'];
            $expires_in = intval( $rs['expires_in'] , 10);
            if ($expires_in <= 0) {
                $expires_in = 5;
            }else if( $expires_in>=7200 ){
                $expires_in = 7000;
            }
            
            $data = array();
            $data['expire_time'] = time() + $expires_in;
            $data['access_token'] = $access_token;
            
            S('access_token', $data, $expires_in);
            return $access_token;
        } else {
            $content = "get access token error:" . $rs1;
            my_log($content);
        }
    } else {
        $content = "get access token error:" . $rs1;
        my_log($content);
    }
    return false;
}



/***
 * 混淆HTML内容，防止微信检测html，降低被封域名风险
 * @param unknown $content
 * @return string
 */
function encrypt_html( $content ){
    if( empty($content)){
        return $content;
    }
    preg_match_all ( "/[\xc2-\xdf][\x80-\xbf]+|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}|[\x01-\x7f]+/e", $content, $r );
    //匹配utf-8字符，
    $str = $r [0];
    $l = count ( $str );
    for($i = 0; $i < $l; $i ++) {
        $value = ord ( $str [$i] [0] );
        if ($value < 223) {
            $str [$i] = rawurlencode ( utf8_decode ( $str [$i] ) );
            //先将utf8编码转换为ISO-8859-1编码的单字节字符，urlencode单字节字符.
            //utf8_decode()的作用相当于iconv("UTF-8","CP1252",$v)。
        } else {
            //                 $str [$i] = "%u" . strtoupper ( bin2hex ( iconv ( "UTF-8", "UCS-2", $str [$i] ) ) );
            $str [$i] = "%u" . strtoupper ( bin2hex ( mb_convert_encoding($str [$i], "UCS-2", "UTF-8") ) );
        }
    }
    $content =  join ( "", $str );

    $content = str_replace('%', "#",$content );

    $function_name = 's';
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol)-1;

    for($i=0;$i<10;$i++){
        $function_name.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    $str = "<meta charset=\"utf-8\"><script charset='UTF-8'>function {$function_name}({$function_name}){document.write( unescape({$function_name}.replace(/#/g,'%')) );}";
    $str .= "{$function_name}('".$content."'); </script>";
    return $str;
}

/**
 * 通知管理员
 * @param unknown $content
 */
function notifyManger($content)
{
    $config_obj = new \Common\Model\ConfigModel();
    $notify_openids = $config_obj->getConfig('NOTIFY_OPENIDS');
    // 通知管理员
    if ($notify_openids)
    {
        $arr = explode('~~~', $notify_openids);

        $weixin_obj = new \Com\Weixin\WeixinApi();

        foreach ($arr as $ii)
        {
            $weixin_obj->sendText($ii, $content);
        }
    }
}